package com.hgyc.mom.core.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hgyc.mom.common.util.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis plus 自动填充字段
 * @author fengwj
 * @since 2019/11/14 0014 18:17
 */
@Slf4j
public class MomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            // 看实体类中是否有这个属性，有的话就执行。没有就不执行
            boolean hasSetter = metaObject.hasSetter("createTime");
            if (hasSetter) {
                setFieldValByName("createTime", LocalDateTime.now(), metaObject);
            }

            Long userId = Long.parseLong((String) StpUtil.getLoginId());
            Object createBy = getFieldValByName("createBy", metaObject);
            if (userId != null && ObjectUtils.isEmpty(createBy)) {
                hasSetter = metaObject.hasSetter("createBy");
                if (hasSetter) {
                    setFieldValByName("createBy", userId, metaObject);
                }
            }
        } catch (Exception e) {
            log.error("自动填充新增信息失败！", e);
            throw new RuntimeException(e);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            // 如果预先自己设置了值，则设置不使用MP的自动填充
            boolean hasSetter = metaObject.hasSetter("updateTime");
            if (hasSetter) {
                setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
            Long userId = Long.parseLong((String) StpUtil.getLoginId());
            if (userId != null) {
                hasSetter = metaObject.hasSetter("updateBy");
                if (hasSetter) {
                    setFieldValByName("updateBy", userId, metaObject);
                }
            }
        } catch (Exception e) {
            log.error("自动填充更新信息失败！", e);
            throw new RuntimeException(e);
        }
    }
}
